import {ExclamationCircleOutlined, PlusOutlined} from '@ant-design/icons';
import {Button, DatePicker, Divider, Drawer, Form, InputNumber, message, Modal, Select, Tag} from 'antd';
import moment from 'moment';
import React, {useEffect, useRef, useState} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import PaymentApplyForm from './components/PaymentApplyForm';
import {
  addFinanceReceivable, finishFinancePayable, finishReceivable,
  queryFinanceReceivable,
  queryReceivableDetail,
  queryReceivedDetail,
  receivableDetailByOrder
} from '@/services/finance';
import {queryCustomer,} from '@/services/customer';
import {queryAccount} from "@/services/system";


const TableList = () => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const [formTitle, setFormTitle] = useState('新增收款');
  const actionRef = useRef();
  const receivableRef = useRef();
  const receivedRef = useRef();
  const receivableDetailRef = useRef();
  const [formRef] = Form.useForm();
  const [row, setRow] = useState();
  const [customerData, setCustomerData] = useState([]);
  const [receivableData, setReceivableData] = useState([]);
  const [receivedData, setReceivedData] = useState([]);
  const [receivedByData, setReceivedByData] = useState([]);
  const [receivableDetailVisible, setReceivableDetailVisible] = useState(false)
  const [receivableDetailParam, setReceivableDetailParam] = useState({})
  const {Option} = Select;
  const {RangePicker} = DatePicker;
  const handleCreateModalVisible = () => {
    setFormTitle('新增收款')
    handleModalVisible(true)
  }
  useEffect(() => {
    queryAccount({
      pageNum: 1,
      pageSize: 999999
    }).then(res => {
      if (res && res.status === '0') {
        setReceivedByData(res.result.records)
      }
    })
  }, [])
  const onCustomerSearch = async (v) => {
    await queryCustomer({
      custName: v,
      pageNum: 1,
      pageSize: 99999
    }).then(res => {
      if (res && res.status === '0') {
        setCustomerData(res.result.records)
      }
    })
  }
  const onCustomerChange = (v, o) => {
    formRef.setFieldsValue({
      custId: o.key
    })
  }
  const handleAdd = async (fields) => {
    const hide = message.loading('正在添加');
    fields.dataMonth = moment(fields.dataMonth, 'YYYY-MM-DD HH:mm:ss').format("YYYYMM")
    try {
      await addFinanceReceivable({...fields}).then(res => {
        if (res && res.status === '0') {
          hide();
          message.success('添加成功');
        } else {
          message.error(res.message)
        }
      });

      return true;
    } catch (error) {
      hide();
      message.error('添加失败请重试！');
      return false;
    }
  };

  const onFinishClick = (record) => {
    Modal.confirm({
      title: '注意',
      icon: <ExclamationCircleOutlined/>,
      content: `是否要完结【${record.custName}】的【${record.dataMonth}】收款？`,
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        finishReceivable(record).then(res=>{
          if (res && res.status === '0') {
            message.success("完结成功")
            if (actionRef.current) {
              actionRef.current.reload()
            }
          }else {
            message.error(res.message)
          }
        })
      }
    });
  }

  const onDetailClick = (record) => {
    setRow(record);
    // if (receivableRef.current) {
    //   receivableRef.current.reload()
    // }
    // if (receivedRef.current) {
    //   receivedRef.current.reload()
    // }
    // queryReceivableDetail(record).then(res=>{
    //   setReceivableData(res.data)
    // })
    // queryReceivedDetail(record).then(res=>{
    //   setReceivedData(res.data)
    // })
  }

  const tableRef = useRef();
  useEffect(() => {
    tableRef.current?.setFieldsValue({
      dataMonth: [moment().subtract(5, "months"), moment()],
    });
    tableRef.current?.submit();
  });

  const columns = [
    {
      title: '序号',
      dataIndex: 'key',
      hideInForm: true,
      hideInSearch: true,
      render: (text, record, index, action) => {
        return `${index + 1}`
      }
    },
    {
      title: '客户名称',
      dataIndex: 'custId',
      copyable: true,
      hideInTable: true,
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: `请选择客户名称`,
          },
        ],
      },
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Select
          showSearch
          defaultActiveFirstOption={false}
          showArrow={false}
          filterOption={false}
          onSearch={(v) => onCustomerSearch(v)}
          // onChange={(v,o)=>onCustomerChange(v, o)}
          notFoundContent={null}
        >
          {customerData.map(item => {
            return <Option value={item.custId} key={item.custId}>{item.custName}</Option>
          })}
        </Select>
      },
    },
    {
      title: '客户名称',
      dataIndex: 'custName',
      copyable: true,
      hideInForm: true
    },
    {
      title: '客户货款月份',
      dataIndex: 'dataMonth',
      formItemProps: {
        rules: [
          {
            required: true,
            message: `请选择货款月份`,
          },
        ],
      },
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        if (type === 'table') {
          return (
            <RangePicker picker="month"/>
          )
        } else {
          return (
            <DatePicker picker="month" style={{width: '100%'}}/>
          )
        }
      },
      render: (text) => {
        return moment(text, 'YYYYMM').format('YYYY-MM')
      }
    },
    {
      title: '应收款截止日',
      dataIndex: 'overdueDate',
      hideInSearch: true,
      hideInForm: true,
      render: (text) => {
        return moment(text, 'YYYY-MM-DD HH:mm:ss').format('YYYY-MM-DD')
      }
    },
    {
      title: '应收款金额（元）',
      dataIndex: 'accountReceivable',
      hideInForm: true,
      hideInSearch: true
    },
    {
      title: '已收款金额（元）',
      dataIndex: 'accountReceived',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '收款金额（元）',
      dataIndex: 'accountReceived',
      hideInSearch: true,
      hideInTable: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: `请输入收款金额`,
          },
          {
            pattern: /^\d+(\.\d{0,2})?$/,
            message: '只能输入两位小数'
          }
        ],
      },
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return (
          <InputNumber
            min={1}
            style={{width: '100%'}}
            formatter={value => `${value}元`}
            parser={value => value.replace('元', '')}
            placeholder={`请输入已收款金额`}
          />
        )
      },
    },
    {
      title: '待收款金额(元)',
      dataIndex: 'remainPayAmount',
      hideInForm: true,
      hideInSearch: true,
      render: (text, record) => {
        return (record.accountReceivable - record.accountReceived).toFixed(2)
      }
    },
    {
      title: '收款完结状态',
      dataIndex: 'receiveStatus',
      hideInForm: true,
      render: (text, record) => {
        return (
          <Tag color={text === 2 ? 'red' : 'green'}>{text === 2 ? '未完结' : '已完结'}</Tag>
        )
      },
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return (
          <Select>
            <Option value={1}>已完结</Option>
            <Option value={2}>未完结</Option>
          </Select>
        )
      },
    },
    {
      title: '是否逾期',
      dataIndex: 'isOverdue',
      hideInForm: true,
      render: (text, record) => {
        return (
          <Tag color={record.isOverdue ? 'red' : 'green'}>{record.isOverdue ? '是' : '否'}</Tag>
        )
      },
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return (
          <Select>
            <Option value={true}>是</Option>
            <Option value={false}>否</Option>
          </Select>
        )
      },
    },
    {
      title: '逾期警告',
      dataIndex: 'isOverdueWarning',
      hideInForm: true,
      render: (text, record) => {
        return (
          <Tag color={record.isOverdueWarning ? 'red' : 'green'}>{record.isOverdueWarning ? '是' : '否'}</Tag>
        )
      },
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return (
          <Select>
            <Option value={true}>是</Option>
            <Option value={false}>否</Option>
          </Select>
        )
      },
    },
    {
      title: '收款人员',
      dataIndex: 'receivedBy',
      hideInSearch: true,
      hideInTable: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: `请输入收款人员`,
          },
        ],
      },
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Select
          defaultActiveFirstOption={false}
          showArrow={false}
          filterOption={false}
          notFoundContent={null}
        >
          {receivedByData.map(item => {
            return <Option value={item.userId} key={item.userId}>{item.staffInfo.realName}</Option>
          })}
        </Select>
      },
    },
    {
      title: '收款时间',
      dataIndex: 'receivedTime',
      valueType: 'dateTime',
      hideInSearch: true,
      hideInTable: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: `请输入收款时间`,
          },
        ],
      },
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return (
          <DatePicker style={{width: '100%'}}/>
        )
      },
    },
    {
      title: '备注',
      dataIndex: 'remark',
      valueType: 'textarea',
      hideInSearch: true,
      hideInTable: true
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a onClick={() => onDetailClick(record)}>
          详情
        </a>,
        <Divider type="vertical" style={{display: record.receiveStatus === 2 ? '' : 'none'}}/>,
        <a onClick={() => onFinishClick(record)} style={{display: record.receiveStatus === 2 ? '' : 'none'}}>
          完结
        </a>,
      ],
    },
  ];

  const detailColumns = [
    {
      title: '序号',
      dataIndex: 'key',
      hideInForm: true,
      hideInSearch: true,
      render: (text, record, index, action) => {
        return `${index + 1}`
      }
    },
    {
      title: '客户名称',
      dataIndex: 'custId',
      copyable: true,
      hideInTable: true,
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: `请选择客户名称`,
          },
        ],
      },
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Select
          showSearch
          defaultActiveFirstOption={false}
          showArrow={false}
          filterOption={false}
          onSearch={(v) => onCustomerSearch(v)}
          // onChange={(v,o)=>onCustomerChange(v, o)}
          notFoundContent={null}
        >
          {customerData.map(item => {
            return <Option value={item.custId} key={item.custId}>{item.custName}</Option>
          })}
        </Select>
      },
    },
    {
      title: '客户名称',
      dataIndex: 'custName',
      copyable: true,
      hideInForm: true
    },
    {
      title: '客户货款月份',
      dataIndex: 'dataMonth',
      formItemProps: {
        rules: [
          {
            required: true,
            message: `请选择货款月份`,
          },
        ],
      },
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        if (type === 'table') {
          return (
            <RangePicker picker="month"/>
          )
        } else {
          return (
            <DatePicker picker="month" style={{width: '100%'}}/>
          )
        }
      },
      render: (text) => {
        return moment(text, 'YYYYMM').format('YYYY-MM')
      }
    },
    {
      title: '应收款截止日',
      dataIndex: 'overdueDate',
      hideInSearch: true,
      hideInForm: true,
      render: (text) => {
        return moment(text, 'YYYY-MM-DD HH:mm:ss').format('YYYY-MM-DD')
      }
    },
    {
      title: '应收款金额（元）',
      dataIndex: 'accountReceivable',
      hideInForm: true,
      hideInSearch: true
    },
    {
      title: '已收款金额（元）',
      dataIndex: 'accountReceived',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '收款金额（元）',
      dataIndex: 'accountReceived',
      hideInSearch: true,
      hideInTable: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: `请输入收款金额`,
          },
          {
            pattern: /^\d+(\.\d{0,2})?$/,
            message: '只能输入两位小数'
          }
        ],
      },
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return (
          <InputNumber
            min={1}
            style={{width: '100%'}}
            formatter={value => `${value}元`}
            parser={value => value.replace('元', '')}
            placeholder={`请输入已收款金额`}
          />
        )
      },
    },
    {
      title: '待收款金额(元)',
      dataIndex: 'remainPayAmount',
      hideInForm: true,
      hideInSearch: true,
      render: (text, record) => {
        return (record.accountReceivable - record.accountReceived).toFixed(2)
      }
    },
    {
      title: '收款完结状态',
      dataIndex: 'receiveStatus',
      hideInForm: true,
      render: (text, record) => {
        return (
          <Tag color={text === 2 ? 'red' : 'green'}>{text === 2 ? '未完结' : '已完结'}</Tag>
        )
      },
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return (
          <Select>
            <Option value={1}>已完结</Option>
            <Option value={2}>未完结</Option>
          </Select>
        )
      },
    },
    {
      title: '是否逾期',
      dataIndex: 'isOverdue',
      hideInForm: true,
      render: (text, record) => {
        return (
          <Tag color={record.isOverdue ? 'red' : 'green'}>{record.isOverdue ? '是' : '否'}</Tag>
        )
      },
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return (
          <Select>
            <Option value={true}>是</Option>
            <Option value={false}>否</Option>
          </Select>
        )
      },
    },
    {
      title: '逾期警告',
      dataIndex: 'isOverdueWarning',
      hideInForm: true,
      render: (text, record) => {
        return (
          <Tag color={record.isOverdueWarning ? 'red' : 'green'}>{record.isOverdueWarning ? '是' : '否'}</Tag>
        )
      },
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return (
          <Select>
            <Option value={true}>是</Option>
            <Option value={false}>否</Option>
          </Select>
        )
      },
    },
  ];

  const onReceivableDetailClick = (record) => {
    setReceivableDetailVisible(true)
    const param = {
      orderCode: record.orderCode,
      orderId: record.orderId,
      dataMonth: row.dataMonth
    }
    setReceivableDetailParam(param)
    if (receivableDetailRef.current) {
      receivableDetailRef.current.reload()
    }
    // receivableDetailByOrder(param).then(res=>{
    //   if (res.status === '0') {
    //     console.log(res.data)
    //   }
    // })
  }

  const paymentDetailcolumns = [
    {
      title: '序号',
      dataIndex: 'key',
      hideInForm: true,
      hideInSearch: true,
      render: (text, record, index, action) => {
        return `${index + 1}`
      }
    },
    {
      title: '订单编号',
      dataIndex: 'orderCode',
    },
    {
      title: '产品编码',
      dataIndex: 'productCode',
    },
    {
      title: '订单数量',
      dataIndex: 'orderNum',
    },
    {
      title: '出货数',
      dataIndex: 'num',
    },
    {
      title: '出货金额(元)',
      dataIndex: 'perAmount',
    },
    {
      title: '缺货数量',
      dataIndex: 'toBeShippedNum',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a onClick={() => onReceivableDetailClick(record)}>
          详情
        </a>,
      ],
    },
  ];
  const hasPaymentcolumns = [
    {
      title: '序号',
      dataIndex: 'key',
      hideInForm: true,
      hideInSearch: true,
      render: (text, record, index, action) => {
        return `${index + 1}`
      }
    },
    {
      title: '收款时间',
      dataIndex: 'receivedTime',
      valueType: 'dateTime',
    },
    {
      title: '收款金额(元)',
      dataIndex: 'accountReceived',
    },
    {
      title: '收款人员',
      dataIndex: 'receivedByName',
    },
    {
      title: '备注',
      dataIndex: 'remark',
    }
  ];

  const receivableDetailCol = [
    {
      title: '序号',
      dataIndex: 'key',
      hideInForm: true,
      hideInSearch: true,
      render: (text, record, index, action) => {
        return `${index + 1}`
      }
    },
    {
      title: '订单编码',
      dataIndex: 'orderCode',
    },
    {
      title: '生产编号',
      dataIndex: 'productionNo',
    },
    {
      title: '产品编码',
      dataIndex: 'productCode',
    },
    {
      title: '出货时间',
      dataIndex: 'createTime',
      valueType: 'dateTime',
    },
    {
      title: '出货数',
      dataIndex: 'num',
    },
    {
      title: '出货金额(元)',
      dataIndex: 'perAmount',
    },
    {
      title: '出货人',
      dataIndex: 'createByName',
    },
  ];


  return (
    <PageContainer>
      <ProTable
        actionRef={actionRef}
        formRef={tableRef}
        rowKey="pkId"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button type="primary" onClick={() => handleCreateModalVisible()}>
            <PlusOutlined/> 新建
          </Button>,
        ]}
        request={async (params, sorter, filter) => {
          console.log(params)
          const param = params.dataMonth ? {
            ...params,
            dataMonth: null,
            pageNum: params.current,
            startDate: moment(params.dataMonth[0], 'YYYY-MM-DD HH:mm:ss').format('YYYYMM'),
            endDate: moment(params.dataMonth[1], 'YYYY-MM-DD HH:mm:ss').format('YYYYMM'),
          } : {...params, dataMonth: null, pageNum: params.current};
          const res = await queryFinanceReceivable(param)
          return {
            data: res.result.records,
            success: true,
            total: res.result.total
          }
        }}
        columns={columns}

      />
      <PaymentApplyForm title={formTitle} onCancel={() => handleModalVisible(false)} modalVisible={createModalVisible}>
        <ProTable
          onSubmit={async (value) => {
            const success = await handleAdd(value);

            if (success) {
              handleModalVisible(false);

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          form={{
            form: formRef,
            layout: 'horizontal',
            labelAlign: 'left'
          }}
          rowKey="pkId"
          type="form"
          columns={columns}
        />
      </PaymentApplyForm>

      <Drawer
        width={800}
        visible={!!row}
        onClose={() => {
          setRow(undefined);
        }}
        closable={false}
      >
        {row?.custName && (
          <>
            <ProDescriptions
              column={2}
              title={row?.custName}
              request={async () => ({
                data: row || {},
              })}
              params={{
                id: row?.custName,
              }}
              columns={detailColumns}
            />
            <ProTable
              actionRef={receivableRef}
              rowKey="pkId"
              headerTitle="应收款明细"
              toolbar={false}
              options={false}
              defaultData={receivableData}
              request={async (params, sorter, filter) => {
                const res = await queryReceivableDetail(row)
                return {
                  data: res.data,
                  success: true,
                  total: res.data.length
                }
              }}
              search={false}
              pagination={false}
              columns={paymentDetailcolumns}
            />
            <ProTable
              actionRef={receivedRef}
              rowKey="pkId"
              headerTitle="已收款明细"
              toolbar={false}
              options={false}
              request={async (params, sorter, filter) => {
                const res = await queryReceivedDetail(row)
                return {
                  data: res.data,
                  success: true,
                  total: res.data.length
                }
              }}
              search={false}
              pagination={false}
              columns={hasPaymentcolumns}
            />
          </>
        )}
      </Drawer>
      <Modal width={800} visible={receivableDetailVisible} footer={null} onOk={() => setReceivableDetailVisible(false)}
             onCancel={() => setReceivableDetailVisible(false)}>
        <ProTable
          actionRef={receivableDetailRef}
          rowKey="pkId"
          toolbar={false}
          options={false}
          request={async (params, sorter, filter) => {
            const res = await receivableDetailByOrder(receivableDetailParam)
            return {
              data: res.data,
              success: true,
              total: res.data.length
            }
          }}
          search={false}
          pagination={false}
          columns={receivableDetailCol}
        />
      </Modal>
    </PageContainer>
  );
};

export default TableList;
